using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using mvcdemo07.Db;
using mvcdemo07.Models;
using mvcdemo07.KeywordModel;

namespace mvcdemo07.Controllers
{
    public class StudentController : Controller
    {
        private readonly Dbsql _db;
        public StudentController()
        {
            _db = new Dbsql();
            var GradeClass01 = new List<GradeClass>
            {
                new GradeClass(){
                    ClassName="1班"
                },
                new GradeClass(){
                    ClassName="2班"
                },
                new GradeClass(){
                    ClassName="3班"
                },
            };
            // _db.GradeClasses.AddRange(GradeClass01);
            // _db.SaveChanges();
        }
        public IActionResult Index()
        {
            var students = _db.Students.Where(x => x.IsDel == false).ToArray();
            return View(students);
        }


        public IActionResult Delete(int id)
        {
            var student = _db.Students.Where(x => x.Id == id && x.IsDel == false).FirstOrDefault();
            student.IsDel = true;
            _db.Students.Update(student);
            _db.SaveChanges();
            return RedirectToAction("index");
        }


        public IActionResult Save(Student student)
        {
            if (student.Id <= 0 || student == null)
            {
                _db.Students.Add(student);
                _db.SaveChanges();
            }
            else
            {
                _db.Students.Update(student);
                _db.SaveChanges();
            }
            return Ok();
        }


        public IActionResult CreateOrEdit(int id)
        {
            var student = _db.Students.Where(x => x.Id == id && x.IsDel == false).FirstOrDefault();
            return View(student);
        }


        public IActionResult Query(Keyword keyword)
        {
            List<Student> students;
            if (keyword == null || keyword.word.Length <= 0)
            {
                students = _db.Students.Where(x => x.IsDel == false).ToList();
            }
            else
            {
                students = _db.Students.Where(x => x.IsDel == false && x.Name.Contains(keyword.word)).ToList();
            }
            return Json(students);
        }
    }
}